<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Admin_BackupController
 * @category   Controller
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */

/**
 * Allows the user to dump their database to a csv for backup purposes.
 *
 * @package    Admin_BackupController
 * @category   Controller
 */
class Admin_BackupController extends Zend_Controller_Action  
{         
    /**
     * Shows the backup index page
     */
    public function indexAction()
    {    	    	              
        $backup = new Ot_Backup();
        
        $form = $backup->_form();
                
        if ($this->_request->isPost()) {
        	
        	if ($form->isValid($_POST)) {
        		
        		$this->_helper->layout->disableLayout();
                $this->_helper->viewRenderer->setNeverRender();
	            
	            $db = Zend_Registry::get('dbAdapter');
	            $tableName = $_POST['tableName'];
	            
	            if (isset($_POST['submitSql'])) {
	                $type = 'sql';
	            } else {
	               $type = 'csv';   
	            }

  	            // this call sends it to the browser too 
	            $backup->getBackup($db, $tableName, $type);
	            
	            $logOptions = array(
                        'attributeName' => 'databaseTableBackup',
                        'attributeId'   => $tableName,
                );
                    
                $this->_helper->log(Zend_Log::INFO, 'Backup of database table ' . $tableName . ' was downloaded', $logOptions);
        	}
        }
        
        $this->view->form = $form;
        
        if (!is_null(`mysqldump`)) {
            $this->view->downloadAllSql = true;
        }
        
        $this->_helper->pageTitle('admin-backup-index:title');
    }
    
    public function downloadAllSqlAction()
    {
        if (!is_null(`mysqldump`)) {
            
            $backup = new Ot_Backup();
            
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNeverRender();
            
            $db = Zend_Registry::get('dbAdapter');
            
            // this call sends it to the browser too 
            $backup->getBackup($db, '', 'sqlAll');
            
            $logOptions = array(
                    'attributeName' => 'databaseTableBackup',
                    'attributeId'   => 'allTables',
            );
                
            $this->_helper->log(Zend_Log::INFO, 'Backup of database table ' . $tableName . ' was downloaded', $logOptions);
        }
    }
}